import frappe
import os
import json
from frappe.utils import get_datetime


def import_workspace_shortcuts():
    """
    导入工作空间快捷方式
    从JSON文件中导入所有工作空间快捷方式到数据库
    """
    try:
        print("🚀 开始导入工作空间快捷方式...")
        
        # 获取workspace目录路径
        workspace_dir = frappe.get_app_path("theme", "workspace")
        
        if not os.path.exists(workspace_dir):
            print("❌ workspace目录不存在，跳过导入")
            return False
        
        # 定义要导入的快捷方式配置
        shortcuts_config = [
            # 采购模块快捷方式
            {
                "dir": "buying_shortcuts",
                "files": [
                    "material_request_shortcut.json",
                    "purchase_order_shortcut.json", 
                    "purchase_invoice_shortcut.json",
                    "supplier_quotation_shortcut.json"
                ]
            },
            # 销售模块快捷方式
            {
                "dir": "selling_shortcuts", 
                "files": [
                    "sales_order_shortcut.json",
                    "sales_invoice_shortcut.json",
                    "quotation_shortcut.json",
                    "customer_shortcut.json"
                ]
            },
            # 库存模块快捷方式
            {
                "dir": "stock_shortcuts",
                "files": [
                    "stock_entry_shortcut.json",
                    "purchase_receipt_shortcut.json",
                    "delivery_note_shortcut.json",
                    "stock_reconciliation_shortcut.json"
                ]
            },
            # 资产模块快捷方式
            {
                "dir": "assets_shortcuts",
                "files": [
                    "asset_shortcut.json",
                    "asset_movement_shortcut.json",
                    "asset_maintenance_shortcut.json",
                    "asset_depreciation_schedule_shortcut.json"
                ]
            },
            # 生产模块快捷方式
            {
                "dir": "manufacturing_shortcuts",
                "files": [
                    "work_order_shortcut.json",
                    "bom_shortcut.json",
                    "production_plan_shortcut.json",
                    "job_card_shortcut.json"
                ]
            },
            # 质量模块快捷方式
            {
                "dir": "quality_shortcuts",
                "files": [
                    "quality_inspection_shortcut.json",
                    "quality_procedure_shortcut.json",
                    "quality_goal_shortcut.json",
                    "quality_review_shortcut.json"
                ]
            },
            # 项目模块快捷方式
            {
                "dir": "projects_shortcuts",
                "files": [
                    "project_shortcut.json",
                    "task_shortcut.json",
                    "timesheet_shortcut.json",
                    "project_template_shortcut.json"
                ]
            },
            # 售后支持模块快捷方式
            {
                "dir": "support_shortcuts",
                "files": [
                    "issue_shortcut.json",
                    "warranty_claim_shortcut.json",
                    "maintenance_schedule_shortcut.json",
                    "maintenance_visit_shortcut.json"
                ]
            },
            # 客户关系模块快捷方式
            {
                "dir": "crm_shortcuts",
                "files": [
                    "lead_shortcut.json",
                    "opportunity_shortcut.json",
                    "campaign_shortcut.json",
                    "newsletter_shortcut.json"
                ]
            }
        ]
        
        imported_count = 0
        
        # 遍历配置并导入
        for config in shortcuts_config:
            dir_path = os.path.join(workspace_dir, config["dir"])
            
            if not os.path.exists(dir_path):
                print(f"⚠️ 目录不存在: {dir_path}")
                continue
            
            for filename in config["files"]:
                file_path = os.path.join(dir_path, filename)
                
                if import_workspace_from_json(file_path):
                    imported_count += 1
        
        print(f"✅ 成功导入 {imported_count} 个工作空间快捷方式")
        return True
        
    except Exception as e:
        frappe.log_error(f"导入工作空间快捷方式时出错: {str(e)}")
        print(f"❌ 导入工作空间快捷方式失败: {str(e)}")
        return False


def import_workspace_from_json(json_file_path):
    """
    从JSON文件导入单个工作空间
    
    Args:
        json_file_path (str): JSON文件路径
        
    Returns:
        bool: 导入是否成功
    """
    try:
        if not os.path.exists(json_file_path):
            print(f"❌ JSON文件不存在: {json_file_path}")
            return False
        
        # 读取JSON文件
        with open(json_file_path, 'r', encoding='utf-8') as f:
            workspace_data = json.load(f)
        
        workspace_name = workspace_data.get("name")
        
        if not workspace_name:
            print(f"❌ JSON文件中缺少name字段: {json_file_path}")
            return False
        
        # 检查工作空间是否已存在
        if frappe.db.exists("Workspace", workspace_name):
            print(f"📝 工作空间已存在，跳过: {workspace_name}")
            return True
        
        # 创建新的工作空间文档
        workspace_doc = frappe.new_doc("Workspace")
        
        # 设置基本字段
        workspace_doc.update({
            "name": workspace_data.get("name"),
            "title": workspace_data.get("title"),
            "label": workspace_data.get("label", workspace_data.get("title")),
            "module": workspace_data.get("module"),
            "parent_page": workspace_data.get("parent_page"),
            "icon": workspace_data.get("icon"),
            "public": workspace_data.get("public", 1),
            "sequence_id": workspace_data.get("sequence_id", 1.0),
            "is_hidden": workspace_data.get("is_hidden", 0),
            "hide_custom": workspace_data.get("hide_custom", 0),
            "for_user": workspace_data.get("for_user", ""),
            "type": workspace_data.get("type", "Link"),
            "link_to": workspace_data.get("link_to"),
            "link_type": workspace_data.get("link_type", "DocType")
        })
        
        # 插入文档
        workspace_doc.insert(ignore_permissions=True)
        
        print(f"✅ 成功导入工作空间: {workspace_name} ({workspace_data.get('title')})")
        return True
        
    except Exception as e:
        frappe.log_error(f"导入工作空间JSON文件时出错 {json_file_path}: {str(e)}")
        print(f"❌ 导入失败 {json_file_path}: {str(e)}")
        return False


def remove_workspace_shortcuts():
    """
    移除工作空间快捷方式
    删除所有由theme创建的工作空间快捷方式
    """
    try:
        print("🗑️ 开始移除工作空间快捷方式...")
        
        # 定义要删除的工作空间名称列表
        shortcuts_to_remove = [
            # 采购模块快捷方式
            "Material Request Shortcut",
            "Purchase Order Shortcut", 
            "Purchase Invoice Shortcut",
            "Supplier Quotation Shortcut",
            # 销售模块快捷方式
            "Sales Order Shortcut",
            "Sales Invoice Shortcut",
            "Quotation Shortcut",
            "Customer Shortcut",
            # 库存模块快捷方式
            "Stock Entry Shortcut",
            "Purchase Receipt Shortcut",
            "Delivery Note Shortcut",
            "Stock Reconciliation Shortcut",
            # 资产模块快捷方式
            "Asset Shortcut",
            "Asset Movement Shortcut",
            "Asset Maintenance Shortcut",
            "Asset Depreciation Schedule Shortcut",
            # 生产模块快捷方式
            "Work Order Shortcut",
            "BOM Shortcut",
            "Production Plan Shortcut",
            "Job Card Shortcut",
            # 质量模块快捷方式
            "Quality Inspection Shortcut",
            "Quality Procedure Shortcut",
            "Quality Goal Shortcut",
            "Quality Review Shortcut",
            # 项目模块快捷方式
            "Project Shortcut",
            "Task Shortcut",
            "Timesheet Shortcut",
            "Project Template Shortcut",
            # 售后支持模块快捷方式
            "Issue Shortcut",
            "Warranty Claim Shortcut",
            "Maintenance Schedule Shortcut",
            "Maintenance Visit Shortcut",
            # 客户关系模块快捷方式
            "Lead Shortcut",
            "Opportunity Shortcut",
            "Campaign Shortcut",
            "Newsletter Shortcut"
        ]
        
        removed_count = 0
        
        for workspace_name in shortcuts_to_remove:
            try:
                if frappe.db.exists("Workspace", workspace_name):
                    frappe.delete_doc("Workspace", workspace_name, ignore_permissions=True)
                    print(f"✅ 成功删除工作空间: {workspace_name}")
                    removed_count += 1
                else:
                    print(f"📝 工作空间不存在，跳过: {workspace_name}")
                    
            except Exception as e:
                print(f"❌ 删除工作空间失败 {workspace_name}: {str(e)}")
                frappe.log_error(f"删除工作空间失败 {workspace_name}: {str(e)}")
        
        print(f"✅ 成功移除 {removed_count} 个工作空间快捷方式")
        return True
        
    except Exception as e:
        frappe.log_error(f"移除工作空间快捷方式时出错: {str(e)}")
        print(f"❌ 移除工作空间快捷方式失败: {str(e)}")
        return False


def check_workspace_shortcuts_status():
    """
    检查工作空间快捷方式状态
    
    Returns:
        dict: 包含状态信息的字典
    """
    try:
        shortcuts_list = [
            # 采购模块快捷方式
            "Material Request Shortcut",
            "Purchase Order Shortcut", 
            "Purchase Invoice Shortcut",
            "Supplier Quotation Shortcut",
            # 销售模块快捷方式
            "Sales Order Shortcut",
            "Sales Invoice Shortcut",
            "Quotation Shortcut",
            "Customer Shortcut",
            # 库存模块快捷方式
            "Stock Entry Shortcut",
            "Purchase Receipt Shortcut",
            "Delivery Note Shortcut",
            "Stock Reconciliation Shortcut",
            # 资产模块快捷方式
            "Asset Shortcut",
            "Asset Movement Shortcut",
            "Asset Maintenance Shortcut",
            "Asset Depreciation Schedule Shortcut",
            # 生产模块快捷方式
            "Work Order Shortcut",
            "BOM Shortcut",
            "Production Plan Shortcut",
            "Job Card Shortcut",
            # 质量模块快捷方式
            "Quality Inspection Shortcut",
            "Quality Procedure Shortcut",
            "Quality Goal Shortcut",
            "Quality Review Shortcut",
            # 项目模块快捷方式
            "Project Shortcut",
            "Task Shortcut",
            "Timesheet Shortcut",
            "Project Template Shortcut",
            # 售后支持模块快捷方式
            "Issue Shortcut",
            "Warranty Claim Shortcut",
            "Maintenance Schedule Shortcut",
            "Maintenance Visit Shortcut",
            # 客户关系模块快捷方式
            "Lead Shortcut",
            "Opportunity Shortcut",
            "Campaign Shortcut",
            "Newsletter Shortcut"
        ]
        
        status = {
            "total": len(shortcuts_list),
            "installed": 0,
            "missing": [],
            "details": []
        }
        
        for workspace_name in shortcuts_list:
            exists = frappe.db.exists("Workspace", workspace_name)
            
            if exists:
                status["installed"] += 1
                workspace_doc = frappe.get_doc("Workspace", workspace_name)
                status["details"].append({
                    "name": workspace_name,
                    "title": workspace_doc.title,
                    "parent_page": workspace_doc.parent_page,
                    "status": "已安装"
                })
            else:
                status["missing"].append(workspace_name)
                status["details"].append({
                    "name": workspace_name,
                    "title": "未知",
                    "parent_page": "未知", 
                    "status": "未安装"
                })
        
        return status
        
    except Exception as e:
        frappe.log_error(f"检查工作空间快捷方式状态时出错: {str(e)}")
        return {
            "total": 0,
            "installed": 0,
            "missing": [],
            "details": [],
            "error": str(e)
        }


def get_workspace_shortcuts_info():
    """
    获取工作空间快捷方式信息
    用于调试和状态检查
    """
    try:
        print("📊 工作空间快捷方式状态检查:")
        print("=" * 50)
        
        status = check_workspace_shortcuts_status()
        
        if "error" in status:
            print(f"❌ 检查状态时出错: {status['error']}")
            return
        
        print(f"总数: {status['total']}")
        print(f"已安装: {status['installed']}")
        print(f"未安装: {len(status['missing'])}")
        print()
        
        print("详细状态:")
        print("-" * 30)
        
        for detail in status["details"]:
            status_icon = "✅" if detail["status"] == "已安装" else "❌"
            print(f"{status_icon} {detail['name']}")
            print(f"   标题: {detail['title']}")
            print(f"   父页面: {detail['parent_page']}")
            print(f"   状态: {detail['status']}")
            print()
        
        if status["missing"]:
            print("未安装的工作空间:")
            for missing in status["missing"]:
                print(f"  - {missing}")
        
        return status
        
    except Exception as e:
        print(f"❌ 获取工作空间快捷方式信息失败: {str(e)}")
        return None